<?php
   /*************************************************\
    TV-Program
    Version: 2.5
    Author: Dmitri M. Furmanoff
    E-mail: furik@mail.ru
    \*************************************************/

    /*************************************************\
    Компонент: Телепрограммы
    Версия: 2.5
    Автор: Дмитрий Фурманов
    E-mail: furik@mail.ru
    \*************************************************/

defined ('_VALID_MOS') or die('Доступ к файлу запрещен.');
/****** Загрузка программ *****/
//
function GetProgram($dir,$week=0,$delold=1,$stat=false)
{
global $database,$mosConfig_absolute_path,$mosConfig_offset;
global $autoup,$codepage,$timedelimeter,$chandelimeter,$weekdelimeter,$program_offset,$newchan;


include($mosConfig_absolute_path."/administrator/components/com_tv/config.tv.php");
$today=time()+($mosConfig_offset*60*60);
$today=getdate($today);
$dayofweek = $today['wday']; 
$dayofweek=$dayofweek?$dayofweek:7;

$progs=Array();
$ds=1;
$wd=1;
$program_count=0;
$channel_count=0;
$new_chan=0;
$cid=-1;
$chan_offset=0;

if($delold==1)
{
$database->setQuery( "DELETE FROM #__tvprogramms");
		if (!$database->query()) {
    		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
                            exit();
		}

}
$order=0;
$first=0;
$week=intval($week);
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) != false) {
        if(filetype($dir . $file)=='file' && ($file!='.' || $file!='..')){
          if(($ff=fopen($dir.$file,'r'))==true)
          {
           while(!feof($ff)){
           $str=fgets($ff,1024);
          // $str=convert_cyr_string($str,$codepage,"w");
           $head=explode($weekdelimeter,$str,2);
		   if(isset($head[1]))
             $head1=explode($chandelimeter,$head[1],2);
        
            switch(trim($head[0]))
					 {
					 case "Понедельник":
					  $wd=1;
            $ds=1;
					  break;
   				 case "Вторник":
					  $wd=2;
            $ds=1;
					  break;
 					 case "Среда":
					  $wd=3;
            $ds=1;
					  break;
					 case "Четверг":
					  $wd=4;
            $ds=1;
					  break;
					 case "Пятница":
					  $wd=5;
            $ds=1;
					  break;
					 case "Суббота":
					  $wd=6;
					  $ds=1;
					  break;
					 case "Воскресенье":
					  $wd=7;
					  $ds=1;
					  break;
					 default:  
            $ds=0;
           break;
					   }
if(!$ds && $cid != -1){ //не было смены блока
$str=implode($weekdelimeter,$head);
if(preg_match("/^[0-9]{1,2}".$timedelimeter."[0-9]{1,2}/",$str))
{
$tm=Array();
while(ereg("([0-9]{1,2})".$timedelimeter."([0-9]{1,2})",$str,$regs))
{
$offs=$regs[1]+$program_offset+$chan_offset;
if($offs>=24)
 $offs-=24;
if($offs<0)
 $offs+=24;
array_push($tm,strval($offs).$timedelimeter.strval($regs[2]));
$str1=split("([0-9]{1,2})".$timedelimeter."([0-9]{1,2})",$str,2);
$str=$str1[1];
}
$program=htmlspecialchars($str, ENT_QUOTES);
foreach($tm as $tt)
{
          $hm=explode($timedelimeter,trim($tt));   

          $order=$hm[0]*100+$hm[1];
          if($first==0)  //это для передач которые идут после 24 часов
            $first=$order;
          if($first>$order)
           $order=($hm[0]+24)*100+$hm[1];


$progs[]="('$cid', '".date("Y.m.d",$dat)."', '$hm[0]','$hm[1]','".$program."', '$order')";			  
$program_count++;

          }   
}
}
          else{     // была смена блока   
              $first=0;
              $order=0;
	  if(isset($head1[1]))
                    $head1[1]=trim($head1[1]);
	   else
    	     $head1[1]="";
              $database->setQuery( "SELECT * FROM #__tvchannels where channelid = '$head1[1]'");
              $rows = $database->loadObjectList();
		          if(!count($rows)) //канал не найден
		           {
                                       if($newchan)  // если хотим добавлять новые каналы
                                      {
   		          $database->setQuery( "INSERT INTO #__tvchannels (channelid,channelname) VALUES ('".$head1[1]."', '".$head1[1]."')"); //добавляем новый
		            if (!$database->query()) {
    		            echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		                exit();
		            }
                                       $new_chan++; 
		           $database->setQuery( "SELECT * FROM #__tvchannels where channelid = '$head1[1]'"); 
 		           $rows = $database->loadObjectList();
		           $cid=$rows[0]->cid;
                                       }
			else 
                                            $cid=-1;
              }
	else //канал найден
                 {
              $cid=$rows[0]->cid;
	$chan_offset=$rows[0]->timeoffset;
	}

             $dat=mktime(0,0,0,$today['mon'],$today['mday']-$dayofweek+$wd+$week*7,$today['year']);
             }
        
          }//файл закончился
          fclose($ff);
          unlink ($p_path="$dir$file");
if(count($progs))
{
		$database->setQuery( "INSERT INTO #__tvprogramms (`channel`, `date`, `hour`, `minute`, `name`, `order`) VALUES ".implode($progs,","));
        if (!$database->query()) {
		         echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
             exit();
		      }
}			  
if($stat)
{
       echo "Загружено:<br>";
       echo "<b>".$program_count."</b> передач<br>";
       echo "и <b>".$new_chan."</b> новых каналов<br>";
}	   
         }
         }
        }
    }
}

return $program_count;
}//

/************************************************************************\
* Автоматически получаем телепрограммы с www.kulichki.tv *
\************************************************************************/
function GetKulichkiTV($week_name)
{
global $mosConfig_absolute_path, $database;

 if(file_exists($mosConfig_absolute_path."/administrator/components/com_tv/program.txt")) //Мамбот уже запущен!
       return 0;

$stop=0;

$kulichkitv=GetKulichkiList("week=$week_name&pakets=sputnik");
if(is_array($kulichkitv))
{
$data="week=$week_name";
$data.='&day=1&day=2&day=3&day=3&day=4&day=5&day=6&day=7';


$database->setQuery( "SELECT * FROM #__tvchannels where published=1"); 
$channels = $database->loadObjectList();
foreach($channels as $channel)
{
if(isset($kulichkitv[$channel->channelid]))
  $data.="&chanel=".urlencode($kulichkitv[$channel->channelid]); 
}

 $out = "POST /andgon/cgi-bin/itv.cgi HTTP/1.1\r\n";
 $out .= "Host: kulichki.tv\r\n"; 
 $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
 $out .= "Content-Length: ".strlen($data)."\r\n\r\n"; 
 $out .= $data."\r\n\r\n"; 

 $fp = fsockopen("kulichki.tv", 80, $errno, $errstr, 10);

 $fff = fopen($mosConfig_absolute_path."/administrator/components/com_tv/program/program.txt", "w");
 
 if ($fp)
  { 
   fputs($fp, $out); 
   while(($gets=fgets($fp,2048)) && !$stop)
       {
$gets = iconv("windows-1251", "UTF-8", $gets);
//        $gets=convert_cyr_string($gets,"k","w");
        $gets=str_replace("<br>","\n",$gets);
        $gets=strip_tags($gets); 
        fputs($fff, $gets, strlen($gets));
		$stop=strpos($gets,"spylog.com");
       }
   fclose($fp);
  } 
  fclose ($fff);
}
}

/********************************************************************\
* Получаем список доступных каналов на  www.kulichki.tv *
\********************************************************************/
function GetKulichkiList($data)
{
global $mosConfig_absolute_path;
include_once($mosConfig_absolute_path."/administrator/components/com_tv/config.tv.php");
$pre_key=0;

$out = "POST /cgi-bin/gpack.cgi HTTP/1.1\r\n";
$out .= "Host: kulichki.tv\r\n"; 
$out .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
$out .= "Content-Length: ".strlen($data)."\r\n\r\n"; 
$out .= $data."\r\n\r\n"; 
$stop=0;
$fp= fsockopen("kulichki.tv", 80, $errno, $errstr, 10);
if ($fp)
{ 
fputs($fp, $out); 
while(($gets=fgets($fp,2048)) && !$stop)
{
$gets = iconv("windows-1251", "UTF-8", $gets);
//$gets=convert_cyr_string($gets,"k","w");
preg_match("/<input type=\"checkbox\" name=\"chanel\" value=\"(.*)/",$gets,$keys);
preg_match("/^\">(.*)<BR>/",$gets,$names);
if(isset($names[1]))
  $kulichkitv[$names[1]]="$pre_key";
if(isset($keys[1]))
  $pre_key=$keys[1];
$stop=strpos($gets,"</form>");  
}
fclose($fp);
}
return $kulichkitv;
}


function GetKulichkiWeekName()
{
global $mosConfig_absolute_path;
 if(($fin=file("http://www.kulichki.tv/"))==true)
 {
    foreach($fin as $finstr)
    {
       preg_match("/<input type=\"hidden\" name=\"week\" value=(\d*)/",$finstr,$keys);
       if(isset($keys[1]))  
            return $keys[1];
     }
   return false;
 }
else
 return false;
}

?>
